package qimao.com.edu.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
    // 设置持久化Cookie（30天）
    public static void setPersistentCookie(HttpServletResponse response, String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setHttpOnly(true); // 防止XSS攻击
        cookie.setMaxAge(30 * 24 * 60 * 60); // 30天有效期
        response.addCookie(cookie);
    }
    /**
     * 设置安全的 HTTP-only Cookie（包含 Secure 标志）
     * @param response HTTP响应对象
     * @param name Cookie名称
     * @param value Cookie值
     * @param maxAge 有效期（秒）
     */
    public static void setSecureHttpOnlyCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setHttpOnly(true); // 防止XSS攻击
        cookie.setSecure(true);   // 仅通过HTTPS传输
        cookie.setMaxAge(maxAge); // 自定义有效期
        response.addCookie(cookie);
    }
    
    // 获取Cookie值
    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
    
    // 清除Cookie
    public static void clearCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}
